package com.qeeyou.apps.android.craftsman.activity.me;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.utils.imageloader.GlideImageLoader;
import com.qeeyou.apps.android.craftsman.po.CommonInfo;
import com.qeeyou.apps.android.craftsman.po.LoginInfo;
import com.qeeyou.apps.android.craftsman.po.UserInfo;
import com.qeeyou.apps.android.craftsman.service.SystemContext;
import com.qeeyou.apps.android.craftsman.service.UserService;
import com.qeeyou.apps.android.craftsman.utils.ImageLoader;
import com.qeeyou.apps.android.craftsman.view.BottomDialog;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;
import com.qeeyou.apps.android.craftsman.view.wheelview.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class PersonInfoActivity extends Activity implements EasyPermissions.PermissionCallbacks {

    private ImageView btnBack;
    private TextView btnSubmit;               //提交按钮
    private LinearLayout btnAvatar;
    private LinearLayout btnName;
    private LinearLayout btnAge;
    private LinearLayout btnMobile;
    private LinearLayout btnAddress;
    private LinearLayout btnGender;
    private LinearLayout btnBirthday;
    private CustomLoadingDialog mLoadingDialog;

    private BottomDialog bottomDialog;

    private String username;
    private String address;
    private String age;
    private String gender;
    private String avatarStr;
    private String birthday;

    private static final int REQUEST_CODE_NAME = 3000;
    private static final int REQUEST_CODE_ADDRESS = 4000;
    private static final int REQUEST_CODE_CHOOSE = 5000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);

        setView();

        setEvent();

        //初始化ImagePicker
        initImagePicker();

        //获取用户信息
        new GetPersonInfo().execute(new String[]{});
    }

    private void setView() {
        btnBack = (ImageView) this.findViewById(R.id.btnBack4PersonInfo);
        btnSubmit = (TextView) this.findViewById(R.id.btnSubmit4PersonInfo);
        btnAvatar = (LinearLayout) this.findViewById(R.id.btnAvatar4PersonInfo);
        btnName = (LinearLayout) this.findViewById(R.id.btnName4PersonInfo);
        btnAge = (LinearLayout) this.findViewById(R.id.btnAge4PersonInfo);
        btnMobile = (LinearLayout) this.findViewById(R.id.btnMobile4PersonInfo);
        btnAddress = (LinearLayout) this.findViewById(R.id.btnAddress4PersonInfo);
        btnGender = (LinearLayout) this.findViewById(R.id.btnGender4PersonInfo);
        btnBirthday = (LinearLayout) this.findViewById(R.id.btnBirthday4PersonInfo);

    }

    private void setEvent() {
        btnAvatar.setOnClickListener(onItemClickListener);
        btnName.setOnClickListener(onItemClickListener);
        btnAge.setOnClickListener(onItemClickListener);
        btnMobile.setOnClickListener(onItemClickListener);
        btnAddress.setOnClickListener(onItemClickListener);
        btnGender.setOnClickListener(onItemClickListener);
        btnBirthday.setOnClickListener(onItemClickListener);
        btnSubmit.setOnClickListener(onSubmitClickListener);
        btnBack.setOnClickListener(onBackClickListener);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d("PersonInfoActivity", "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d("PersonInfoActivity", "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_ADDRESS) {
            if(resultCode == RESULT_OK) {
                //TODO -- 地址
                String address = data.getStringExtra("user_address");
                TextView txtvAddress = (TextView) btnAddress.getChildAt(1);
                PersonInfoActivity.this.address = address;
                txtvAddress.setText(PersonInfoActivity.this.address);
            } else {
                TextView txtvAddress = (TextView) btnAddress.getChildAt(1);
                PersonInfoActivity.this.address = "";
                txtvAddress.setText(PersonInfoActivity.this.address);
            }
        } else if(requestCode == REQUEST_CODE_NAME) {
            if(resultCode == RESULT_OK) {
                //TODO -- 姓名
                String name = data.getStringExtra("user_name");
                TextView txtvUserName = (TextView) btnName.getChildAt(1);
                PersonInfoActivity.this.username = name;
                txtvUserName.setText(PersonInfoActivity.this.username);
            } else {
                TextView txtvUserName = (TextView) btnName.getChildAt(1);
                PersonInfoActivity.this.username = "";
                txtvUserName.setText(PersonInfoActivity.this.username);
            }
        } else if (requestCode == REQUEST_CODE_CHOOSE) {
            ImageView imgvAvatar = (ImageView) btnAvatar.getChildAt(2);
            if(resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem item = images.get(0);
                ImageLoader.getInstance().displayImage(PersonInfoActivity.this, item.path, imgvAvatar);
                avatarStr = item.path;
            } else {
                ImageLoader.getInstance().displayImageById(PersonInfoActivity.this, R.drawable.ic_message_avatar, imgvAvatar);
                avatarStr = null;
            }
        }
    }

    //TODO -- 提交信息
    private View.OnClickListener onSubmitClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(avatarStr != null) {
                String[] params = new String[]{avatarStr};
                new UploadUserAvatar().execute(params);
            } else {
                submitUserInfo();
            }
        }
    };

    //返回按钮
    private View.OnClickListener onBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PersonInfoActivity.this.finish();
        }
    };

    //初始化ImagePicker
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    //item点击事件
    private View.OnClickListener onItemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(view == btnAvatar) {
                //TODO -- 头像
                if(EasyPermissions.hasPermissions(PersonInfoActivity.this,
                        new String[]{Manifest.permission.CAMERA,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                        })) {
                    Intent intent = new Intent(PersonInfoActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_CHOOSE);
                } else {
                    EasyPermissions.requestPermissions(
                            PersonInfoActivity.this,
                            getString(R.string.permission_request_denied),
                            REQUEST_CODE_CHOOSE,
                            new String[]{
                                    Manifest.permission.CAMERA,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE});
                }
            } else if(view == btnName) {
                //TODO -- 姓名
                Intent intent = new Intent(PersonInfoActivity.this, EditInfoActivity.class);
                TextView txtvUserName = (TextView) btnName.getChildAt(1);
                String username = txtvUserName.getText().toString();
                intent.putExtra("edit_title", "姓名");
                intent.putExtra("edit_content", username);
                PersonInfoActivity.this.startActivityForResult(intent, REQUEST_CODE_NAME);
            } else if(view == btnAge) {
                //TODO -- 年龄
                View dialogView = LayoutInflater.from(PersonInfoActivity.this).inflate(R.layout.dialog_age_selector, null);
                WheelView wheelView1 = dialogView.findViewById(R.id.wheelView4AgeSelector);
                Button btnConfirm = (Button) dialogView.findViewById(R.id.btnConfirm4AgeSelector);
                Button btnCancel = (Button)dialogView.findViewById(R.id.btnCancel4AgeSelector);
                wheelView1.setItems(getAges(),0);//init selected position is 0 初始选中位置为0
                age = "18岁";
                wheelView1.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(int selectedIndex, String item) {
                        Log.d("InstallNum", "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item);
                        age = item;
                    }
                });
                btnConfirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView txtvView = (TextView) btnAge.getChildAt(1);
                        txtvView.setText(age);
                        bottomDialog.dismiss();
                    }
                });
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });
                //防止弹出两个窗口
                if (bottomDialog !=null && bottomDialog.isShowing()) {
                    return;
                }
                bottomDialog = new BottomDialog(PersonInfoActivity.this, R.style.ActionSheetDialogStyle);
                //将布局设置给Dialog
                bottomDialog.setContentView(dialogView);
                bottomDialog.show();//显示对话框
            } else if(view == btnMobile) {
                //TODO -- 电话
                Toast.makeText(PersonInfoActivity.this, "联系方式暂时不用修改", Toast.LENGTH_SHORT).show();
                return;
            } else if(view == btnAddress) {
                //TODO -- 居住地址
                TextView txtvAddress = (TextView) btnAddress.getChildAt(1);
                String address = txtvAddress.getText().toString();
                Intent intent = new Intent(PersonInfoActivity.this, EditInfoActivity.class);
                intent.putExtra("edit_title", "居住地址");
                intent.putExtra("edit_content", address);
                PersonInfoActivity.this.startActivityForResult(intent, REQUEST_CODE_ADDRESS);
            } else if(view == btnGender) {
                //TODO -- 性别
                View dialogView = LayoutInflater.from(PersonInfoActivity.this).inflate(R.layout.dialog_gender_selector, null);
                WheelView wheelView1 = dialogView.findViewById(R.id.wheelView4GenderSelector);
                Button btnConfirm = (Button) dialogView.findViewById(R.id.btnConfirm4GenderSelector);
                Button btnCancel = (Button)dialogView.findViewById(R.id.btnCancel4GenderSelector);
                wheelView1.setItems(getGenders(),0);//init selected position is 0 初始选中位置为0
                gender = "男";
                wheelView1.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(int selectedIndex, String item) {
                        gender = item;
                    }
                });
                btnConfirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView txtvView = (TextView) btnGender.getChildAt(1);
                        txtvView.setText(gender);
                        bottomDialog.dismiss();
                    }
                });
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });
                //防止弹出两个窗口
                if (bottomDialog !=null && bottomDialog.isShowing()) {
                    return;
                }
                bottomDialog = new BottomDialog(PersonInfoActivity.this, R.style.ActionSheetDialogStyle);
                //将布局设置给Dialog
                bottomDialog.setContentView(dialogView);
                bottomDialog.show();//显示对话框
            } else {
                //TODO -- 生日
                TimePickerView pickerView = new TimePickerView.Builder(PersonInfoActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
                        TextView birthdayTextView = (TextView) btnBirthday.getChildAt(1);
                        birthdayTextView.setText(dateStr);
                        birthday = dateStr;
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .setRange(Calendar.getInstance().get(Calendar.YEAR) - 100, Calendar.getInstance().get(Calendar.YEAR) + 20 ).build();
                pickerView.setDate(Calendar.getInstance());
                pickerView.show();
                return;
            }
        }
    };

    //上传用户头像
    class UploadUserAvatar extends AsyncTask<String, Void, List<String>> {
        public UploadUserAvatar() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(PersonInfoActivity.this);
            }
            mLoadingDialog.setMessage("正在保存用户信息...");
            mLoadingDialog.show();
        }

        @Override
        protected List<String> doInBackground(String... params) {
            String imagePath = params[0];
            List<String> imagePaths = new ArrayList<String>();
            imagePaths.add(imagePath);
            List<String> filePaths = AppService.getInstance().uploadImages(imagePaths);
            return filePaths;
        }

        @Override
        protected void onPostExecute(List<String> result) {
            super.onPostExecute(result);
            if(result != null && !result.isEmpty()) {
                avatarStr = result.get(0);
                avatarStr = avatarStr.replace(";", "");
                LoginInfo loginInfo = SystemContext.getInstance().getLoginInfo();
                loginInfo.setAvator(avatarStr);
                SystemContext.getInstance().setLoginInfo(loginInfo);
                //提交用户信息
                submitUserInfo();
            } else {
                if(mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                    mLoadingDialog = null;
                }
                Toast.makeText(PersonInfoActivity.this, "提交头像信息失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //提交用户信息
    private void submitUserInfo() {
        String nameStr = ((TextView)btnName.getChildAt(1)).getText().toString();
        if(nameStr == null) {
            nameStr = "";
        }
        String ageStr = ((TextView)btnAge.getChildAt(1)).getText().toString();
        if(ageStr != null) {
            ageStr = ageStr.substring(0, ageStr.indexOf("岁"));
        } else {
            ageStr = "";
        }
        String genderStr = ((TextView)btnGender.getChildAt(1)).getText().toString();
        genderStr = (genderStr != null && genderStr.equalsIgnoreCase("男")) ? "1" : "2";
        String addressStr = ((TextView)btnAddress.getChildAt(1)).getText().toString();
        if(addressStr == null) {
            addressStr = "";
        }
        String birthdayStr = ((TextView)btnBirthday.getChildAt(1)).getText().toString();
        if(birthdayStr == null) {
            birthdayStr = "";
        }
        //TODO -- 经纬度地址待定
        String coordinates = "121.351303,31.387385";
        String avatar = avatarStr;
        String params[] = {nameStr, ageStr, genderStr, addressStr, coordinates, avatar, birthdayStr};
        new ModifyPersonInfo().execute(params);
    }

    class ModifyPersonInfo extends AsyncTask<String, Void, CommonInfo> {
        public ModifyPersonInfo() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(PersonInfoActivity.this);
            }
            mLoadingDialog.setMessage("正在保存用户信息...");
            mLoadingDialog.show();
        }

        @Override
        protected CommonInfo doInBackground(String... params) {
            String name = params[0];
            String age = params[1];
            String gender = params[2];
            String address = params[3];
            String coordinates = params[4];
            String avatar = params[5];
            String birthday = params[6];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("name", name);
            paramMap.put("sex", gender);
            paramMap.put("age", age);
            paramMap.put("address", address);
            paramMap.put("coordinates", coordinates);
            paramMap.put("avatar", avatar);
            paramMap.put("birthday", birthday);
            CommonInfo resultInfo = UserService.getInstance().modifyUserInfo(paramMap);
            return resultInfo;
        }

        @Override
        protected void onPostExecute(CommonInfo resultInfo) {
            super.onPostExecute(resultInfo);
            if(mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if(resultInfo != null && resultInfo.getStatus().equalsIgnoreCase("1")) {
                Toast.makeText(PersonInfoActivity.this, "保存用户信息成功", Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        PersonInfoActivity.this.finish();
                    }
                }, 800);
            } else {
                Toast.makeText(PersonInfoActivity.this, "保存用户信息失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

    //获取个人信息
    class GetPersonInfo extends AsyncTask<String, Void, UserInfo> {
        public GetPersonInfo() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(PersonInfoActivity.this);
            }
            mLoadingDialog.setMessage("正在获取用户信息...");
            mLoadingDialog.show();
        }

        @Override
        protected UserInfo doInBackground(String... params) {
            Map<String, String> paramMap = new HashMap<String, String>();
            UserInfo resultInfo = UserService.getInstance().getUserInfo(paramMap);
            return resultInfo;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);
            if(mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if(userInfo != null) {
                //TODO -- 获取用户信息成功
                String avatar = userInfo.getAvatar();
                ImageView imgvAvatar = (ImageView) btnAvatar.getChildAt(2);
                if(avatar != null && !avatar.trim().equalsIgnoreCase("")) {
                    avatar = avatar.replace(";", "");
                    String imageUrl = ImageLoader.getInstance().getImageUrl(avatar);
                    ImageLoader.getInstance().displayHeaderPic(PersonInfoActivity.this, imageUrl, imgvAvatar);
                } else {
                    Glide.with(PersonInfoActivity.this).load(R.drawable.ic_message_avatar).into(imgvAvatar);
                }
                String username = userInfo.getName();
                TextView txtvUserName =  (TextView) btnName.getChildAt(1);
                txtvUserName.setText(username);

                String sex = userInfo.getSex();
                TextView txtvGender =  (TextView) btnGender.getChildAt(1);
                if(sex != null && (sex.trim().equalsIgnoreCase("1")
                        || sex.trim().equalsIgnoreCase("男"))) {
                    txtvGender.setText("男");
                } else {
                    txtvGender.setText("女");
                }

                String age = userInfo.getAge();
                if(age == null || age.trim().equalsIgnoreCase("")) {
                    age = "未知";
                } else {
                    age = age + "岁";
                }
                TextView txtvAge =  (TextView) btnAge.getChildAt(1);
                txtvAge.setText(age);

                String address = userInfo.getAddress();
                TextView txtvAddress =  (TextView) btnAddress.getChildAt(1);
                if(address == null) {
                    address = "未知地址";
                }
                txtvAddress.setText(address);

                String phone = userInfo.getPhone();
                TextView txtvPhone =  (TextView) btnMobile.getChildAt(1);
                txtvPhone.setText(phone);

                String birthday = userInfo.getBirthday();
                TextView txtvBirthday =  (TextView) btnBirthday.getChildAt(1);
                txtvBirthday.setText(birthday);

            } else {
                Toast.makeText(PersonInfoActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private ArrayList getAges() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 18; i < 70; i++) {
            list.add(i + "岁");
        }
        return  list;
    }

    private ArrayList<String> getGenders() {
        ArrayList<String> genderList = new ArrayList<String>();
        genderList.add("男");
        genderList.add("女");
        return genderList;
    }
}
